<template>
  <div class="title pl-14px">轨迹查询</div>
  <div class="option-content">
    <el-form ref="basicFormRef" :model="basicParams" :rules="basicRules" status-icon>
      <div class="label">车牌号码</div>
      <el-form-item prop="carNumber">
        <el-select
          v-model="basicParams.deviceId"
          filterable
          remote
          placeholder="请选择"
          :remote-method="remoteMethod"
          :loading="carLoading"
          style="width: 100%"
          clearable
          @change="handleCarChange"
        >
          <el-option v-for="item in carOptions" :key="item.id" :label="item.carNumber" :value="item.deviceId">
            {{ item.carNumber }}
          </el-option>
        </el-select>
      </el-form-item>

      <div class="label">设备ID</div>
      <el-form-item prop="deviceId">
        <el-input v-model="basicParams.deviceId" disabled />
      </el-form-item>

      <div class="label">选择时间</div>
      <el-form-item prop="startTime">
        <date-picker v-model:start="basicParams.startTime" v-model:end="basicParams.endTime" />
      </el-form-item>
    </el-form>

    <div class="flex-x-c">
      <el-button class="submit-btn" type="primary" :loading="btnLoading" :style="{ width: '200px' }" @click="getCarData">查询</el-button>
    </div>
  </div>

  <!-- 停车记录 -->
  <div class="stop-record mt-15px">
    <div class="stop-tip">
      停车时长[分]
      <span class="stop-des">(注:停车时间大于阈值，记录停车点)</span>
    </div>
    <el-input v-model="basicParams.time" :prefix-icon="Search" class="stop-input">
      <template #append>
        <el-button type="primary" :loading="btnLoading" @click="getStopsRecord">搜索</el-button>
      </template>
    </el-input>
  </div>

  <el-scrollbar class="record-list">
    <template v-if="parkingLotList.length">
      <div v-for="(p, index) in parkingLotList" :key="p.deviceId" class="record-item" @click="handleParkClick(p)">
        <p class="record-item-title">
          <span>{{ index + 1 }}</span>
          停车记录
        </p>
        <div class="record-item-content">
          <div class="record-item-label">开始时间</div>
          <div class="record-item-val">{{ p.parkStartTime }}</div>
        </div>
        <div class="record-item-content">
          <div class="record-item-label">结束时间</div>
          <div class="record-item-val">{{ p.parkOverTime }}</div>
        </div>
        <div class="record-item-content">
          <div class="record-item-label">停车时长</div>
          <div class="record-item-val">{{ p.time }}</div>
        </div>
        <div class="record-item-content">
          <div class="record-item-label">停车地址</div>
          <div class="record-item-val">{{ p.address }}</div>
        </div>
      </div>
    </template>
    <el-empty v-else description="暂无停车点数据" :image-size="80" />
  </el-scrollbar>
</template>

<script lang="ts" setup>
import { useRequest } from '@/hooks/useRequest'
import moment from 'moment'
import { ElMessage } from 'element-plus'
import { FormInstance, FormRules } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getDeviceByCarNumber, getCarDataList, getCarParkRecord } from '@/api/vehicle-track/vehicleTrack'
import type { ParkRecordQuery, ParkRecordData, VehicleTrackData } from '@/api/vehicle-track/vehicleTrack'

const emit = defineEmits<{
  (e: 'handleRenderCarLine', data: VehicleTrackData[]): void
  (e: 'handleRenderParkingMarker', data: Array<ParkRecordData>): void
  (e: 'handleRenderParkingInfo', data: ParkRecordData): void
}>()

const basicParams = reactive<ParkRecordQuery>({
  startTime: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
  time: 30
})
const parkingLotList = ref<ParkRecordData[]>([])

const basicFormRef = ref<FormInstance>()
const validatorDataRange = (rule, value: string, callback) => {
  if (!value) {
    return callback(new Error('请选择时间'))
  }
  const tenDay = 10 * 24 * 3600 * 1000
  const startTime = Date.parse(value)
  const endTime = Date.parse(basicParams.endTime)
  if (Math.abs(endTime - startTime) >= tenDay) {
    return callback(new Error('可查询时间最长为10天'))
  } else {
    return callback()
  }
}
const basicRules = reactive<FormRules>({
  carNumber: [{ required: true, message: '请选择车牌号码', trigger: 'blur' }],
  startTime: [{ required: true, trigger: 'change', validator: validatorDataRange }]
})

// 查询车辆轨迹
const { runAsync: fetchCarDataList, loading: btnLoading } = useRequest(getCarDataList, { manual: true })

const getCarData = () => {
  basicFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const { result: carTrackList } = await fetchCarDataList({ ...basicParams })

        const carTrackData = carTrackList || []
        if (!carTrackData.length) ElMessage.warning('该时间段暂无轨迹！')
        emit('handleRenderCarLine', carTrackData)
        getStopsRecord()
      } catch (err) {
        console.log(err)
      }
    }
  })
}

// 获取停车记录列表
const { runAsync: fetchStopsRecord } = useRequest(getCarParkRecord, { manual: true })

const getStopsRecord = () => {
  basicFormRef.value.validate(async valid => {
    if (valid) {
      const reg = /(^[1-9]\d*$)/
      if (!reg.test(String(basicParams.time))) {
        ElMessage.error('请输入正整数停车时长！')
        return
      }

      btnLoading.value = true
      try {
        const { result: stopsRecordList } = await fetchStopsRecord({ ...basicParams })

        parkingLotList.value = stopsRecordList || []
        emit('handleRenderParkingMarker', parkingLotList.value)
      } finally {
        btnLoading.value = false
      }
    }
  })
}

const handleParkClick = (p: ParkRecordData) => {
  emit('handleRenderParkingInfo', p)
}

// 获取车牌号码下拉数据
const { runAsync: fetchDeviceByCarNumber, data: carListData, loading: carLoading } = useRequest(getDeviceByCarNumber, { manual: true })
const carOptions = computed(() => carListData.value?.result || [])

const remoteMethod = (query: string) => {
  if (!query) return
  fetchDeviceByCarNumber(query)
}

const handleCarChange = (val: string) => {
  basicParams.carNumber = carOptions.value.find(item => item.deviceId === val)?.carNumber
}

onMounted(async () => {
  const query = useRoute().query as Record<string, string>
  if (Object.keys(query).length > 0 && query.carNumber) {
    basicParams.carNumber = query.carNumber
    basicParams.deviceId = query.deviceId
    if (query.startTime) basicParams.startTime = query.startTime
    if (query.endTime) basicParams.endTime = query.endTime
    await fetchDeviceByCarNumber(basicParams.carNumber)
    getCarData()
  }
})
</script>

<style lang="scss" scoped>
.title {
  height: 46px;
  line-height: 46px;
  background: var(--el-color-primary-light-9);
  font-size: var(--el-font-size-medium);
  color: var(--el-text-color-primary);
  position: relative;

  &::before {
    content: '';
    width: 3px;
    height: 13px;
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    background-color: var(--el-color-primary);
  }
}

:deep(.el-input-group__append) {
  background-color: var(--el-color-primary);
}

:deep(.el-input-group__append button.el-button) {
  color: var(--el-color-white);
  background-color: var(--el-color-primary);
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

:deep(.el-date-editor.el-date-editor--datetimerange) {
  min-width: 0;
}
:deep(.el-date-editor .el-range__icon) {
  display: none !important;
}

:deep(.el-range-input) {
  width: 40% !important;
}

:deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

.option-content {
  padding: 0 12px;
  overflow: hidden;

  .label {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 14px;
    color: var(--el-text-color-regular);
    margin: 12px 0 6px 0;
  }
}

.date-btnGroup {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.submit-btn {
  position: relative;
  right: 0;
}

.stop-record {
  padding: 0 12px;
  .stop-tip {
    font-family: PingFangSC-Medium;
    font-size: 14px;
    color: var(--el-text-color-primary);
  }

  .stop-des {
    font-size: 12px;
    font-weight: normal;
    color: var(--el-text-color-regular);
  }

  .stop-input {
    margin-top: 8px;
  }
}

.record-list {
  height: calc(100% - 400px);
  padding: 10px 0;
}

.record-item {
  min-height: 149px;
  background: var(--el-bg-color-overlay);
  border: 1px solid transparent;
  box-shadow: var(--el-box-shadow-light);
  border-radius: 6px;
  box-sizing: border-box;
  padding: 0 10px;
  margin: 10px 32px;
  cursor: pointer;

  &:hover {
    border: 1px solid var(--el-color-primary);
  }

  .record-item-title {
    height: 34px;
    font-weight: 400;
    font-size: 14px;
    color: var(--el-text-color-primary);
    display: flex;
    align-items: center;
    border-bottom: 1px solid var(--el-border-color);
    margin: 0 0 5px;

    span {
      width: 14px;
      height: 14px;
      background: var(--el-color-primary);
      color: var(--el-color-white);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 10px;
      border-radius: 50%;
      margin-right: 5px;
    }
  }

  .record-item-content {
    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 12px;
    color: var(--el-text-color-regular);
    display: flex;
    margin-bottom: 5px;

    .record-item-label {
      width: 66px;
    }

    .record-item-val {
      flex: 1;
    }
  }
}
</style>
